<template>
  <div>
    <search></search>
    <div class="search">
      <input type="text" placeholder="搜索" v-model="value"/>
    </div>
    <ul class="addCount">
        <li v-for="item in tipsList" :key="item.id" @click="infoRoute(item)">{{item.name}} 地址:{{item.address}}</li>
    </ul>
    <div class="map">
      <h2>显示当前位置:</h2>
      <div id="container"></div>
    </div>
  </div>
</template>


<script>
import search from "@/components/search";
export default {
  data() {
    return {
      value: "",
      city:"",
      tipsList:[]
    };
  },
  watch:{
      value(){
        var _this = this;
         AMap.plugin('AMap.Autocomplete', function(){
            // 实例化Autocomplete
            var autoOptions = {
                //city 限定城市，默认全国
                city: _this.city
            }
            var autoComplete= new AMap.Autocomplete(autoOptions);
            autoComplete.search(_this.value, function(status, result) {
                // 搜索成功时，result即是对应的匹配数据
                console.log(result);
                _this.tipsList = result.tips;
            })
        }) 
      }
  },
  methods: {
      infoRoute(val){
          this.$store.commit("updated",val)
          this.$router.replace('/home')
      }
  },
  components: {
    search,
  },
  mounted() {
    var _this = this;
    if(this.$store.state.searchResult.name){  //显示点击的地图位置及添加标记
      var position = this.$store.state.searchResult
     var map = new AMap.Map("container",{
        center: [position.location.lng,position.location.lat],
        zoom: 18
     });
      var marker = new AMap.Marker({
          position:[position.location.lng,position.location.lat]//位置
      })
      map.add(marker);//添加到地图
    }else{   //默认地图显示
      var map = new AMap.Map("container");
      AMap.plugin("AMap.CitySearch", function () {
        var citySearch = new AMap.CitySearch();
        citySearch.getLocalCity(function (status, result) {
          if (status === "complete" && result.info === "OK") {
            // 查询成功，result即为当前所在城市信息
            console.log(result);
            _this.city = result.city;
          }
        });
      });
    }
  },
};
</script>

<style scoped lang="scss">
.search {
  margin: 5px 16px;
  width: 90%;
  height: 44px;
  border: 2px solid #c3c3c3;
  display: flex;
  border-radius: 0.13333rem;
  input {
    padding: 10px 16px;
    height: 24px;
    margin: 0;
    border: 0;
  }
  input::-webkit-input-placeholder {
    color: #ccc;
  }
  input::-moz-input-placeholder {
    color: #ccc;
  }
  input::-ms-input-placeholder {
    color: #ccc;
  }
}
.addCount {
  height: 315px;
  width: 100%;
  overflow: scroll;
  li{
      text-align: left;
      padding: 10px 15px;
  }
}
.map {
  h2 {
    text-align: left;
    padding: 10px;
    margin: 0;
  }
  #container {
    width: 100%;
    height: 200px;
  }
}
</style>